package auth

import (
	"fmt"
	"meman/libs/utils"
	"encoding/json"
	"errors"
	"meman/sys/basic"
)


type Auth struct {

}


func (auth *Auth) Login(token, username string) (*User, error) {
	sessionId := auth.genAuthSessionId(token, username)
	userInfo, err := auth.getUserInfo(sessionId)
	if err != nil {
		return nil, fmt.Errorf("Auth: Login() getUserInfo error:%s", err.Error())
	}
	if userInfo != nil && userInfo.Username != "" {
		groupRoles,err := getGroupRoles(userInfo.Username)
		if err != nil {
			return nil, fmt.Errorf("Auth: Login() getGroupRoles error:%s", err.Error())
		}

		userInfo.AuthSessionId = sessionId
		userInfo.GroupPaths = *groupRoles
		tmpUser := User{}
		tmpUser.Info = *userInfo

		user, err := tmpUser.login()
		if err != nil {
			return nil, fmt.Errorf("Auth: Login() user login()  error:%s", err.Error())
		}

		return user, nil
	}

	return nil, errors.New("Auth: userInfo or userInfo.UserName is empty")

}

func (auth *Auth) genAuthSessionId(token,username string) string {
	return utils.GetSHA1(fmt.Sprintf("%s%s%s",token, basic.Config.Auth.AppKey, username))
}

func(auth *Auth) getUserInfo(sessionId string) (*Info, error) {
	url := fmt.Sprintf("%s%s?session_id=%s", basic.Config.Auth.BaseUrl, basic.Config.Auth.InfoPath, sessionId)
	responses, err := utils.RemoteContent(url)
	if err != nil {
		return nil, fmt.Errorf("Auth: get http content err:%s", err.Error())
	}
	var userInfo *Info
	err = json.Unmarshal(responses, &userInfo)
	if err != nil {
		return nil, fmt.Errorf("Auth: json unmarshal user info error!err:%s", err.Error())
	}

	return userInfo, nil
}